package com.mall.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.DTO.AdminDTO;
import com.mall.pojo.Admin;
import com.mall.service.IAdminService;
import com.mall.utils.R;
import com.mall.vo.AdminVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 超级管理员管理普通管理员
 *
 * @author xiao-chen
 * @since 2023-04-20
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@SaCheckLogin
public class AdminController {
    @Resource
    private IAdminService adminService;

    /**
     * 超级管理员分页查询管理员信息
     *
     * @param page      页号 不传默认是1
     * @param pageSize  页大小 不传默认是2
     * @param adminName 管理员账号
     * @return com.mall.utils.R<HashMap < String, Object>>
     * @author cxx
     * @date 2023/4/26 21:52
     */
    @GetMapping("/list")
    @SaCheckPermission("admin-query")
    @Cacheable(value = "Admin", unless = "#result.data.size()==0")
    public R<Object> list(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page, @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(name = "adminName", required = false) String adminName) {
        Page<Admin> usersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(adminName), Admin::getUsername, DigestUtils.md5Hex(adminName.getBytes())).eq(Admin::getIsSuper, 0);
        adminService.page(usersPage, queryWrapper);
        if (usersPage.getTotal() == 0) {
            return R.error("不存在该管理员账户", usersPage.getRecords());
        }
        List<AdminDTO> adminDTOList = usersPage.getRecords().stream().map(item -> {
            AdminDTO adminDTO = new AdminDTO();
            BeanUtils.copyProperties(item, adminDTO);
            if (item.getIsSuper() == 1) {
                adminDTO.setRole("超级管理员");
            } else {
                adminDTO.setRole("普通管理员");
            }
            return adminDTO;
        }).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("records", adminDTOList);
        map.put("total", usersPage.getTotal());
        log.error(usersPage.getRecords().toString());
        return R.success(map);
    }

    /**
     * 添加一个管理员
     *
     * @param admin 管理员的各种信息
     * @return com.mall.utils.R<java.lang.String>
     * @author cxx
     * @date 2023/4/26 21:43
     */
    @PostMapping("/add")
    @SaCheckPermission("admin-save")
    @CacheEvict(value = "Admin", allEntries = true)
    public R<String> add(@RequestBody AdminVo admin) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(admin.getUsername()), Admin::getUsername, DigestUtils.md5Hex(admin.getUsername().getBytes()));
        List<Admin> list = adminService.list(wrapper);
        if (ObjectUtils.isNotEmpty(list)) {
            return R.error("添加失败,管理员账号已经存在!");
        }
        Admin adminDetail = new Admin();
        admin.setUsername(DigestUtils.md5Hex(admin.getUsername().getBytes()));
        admin.setPassword(DigestUtils.md5Hex(admin.getPassword().getBytes()));
        BeanUtils.copyProperties(admin, adminDetail);
        boolean save = adminService.save(adminDetail);
        return save ? R.success("添加管理员成功!") : R.error("添加失败!");
    }

    /**
     * 超级管理员批量删除管理员
     *
     * @param adminIds 管理员id集合
     * @return com.mall.utils.R<java.lang.String>
     * @author cxx
     * @date 2023/4/26 22:06
     */

    @DeleteMapping("/delete/{adminIds}")
    @SaCheckPermission("admin-delete")
    @CacheEvict(value = "Admin", allEntries = true)
    public R<String> delete(@PathVariable List<Long> adminIds) {
        log.error(adminIds.toString());
        boolean b = adminService.removeBatchByIds(adminIds);
        return b ? R.success("删除成功!") : R.error("删除失败!");
    }

}
